﻿using UnityEditor;
using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Renderer/Export/FBX",
            "Exports a single skinned mesh and any necessary transforms." +
            "Multi-frame Blend-shapes, Blend-shape Normals, and Blend-shape Tangents are not supported.", 0)]
        public static void RendererExportFBX()
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Renderer>();
                if (SkinnEx.IsNullOrNotInAScene(context) || string.IsNullOrEmpty(context.name)) continue;
                if (!SkinnEx.HasMinimumRequirements(context)) continue;
                string path = EditorUtility.SaveFilePanelInProject("Export FBX", context.name, "fbx", "ACSIIFBX");
                if (path == "") continue;
                if (!path.EndsWith(".fbx")) Debug.LogWarning("file path should end with .FBX");
                string fbx;
                if (context as SkinnedMeshRenderer) fbx = (context as SkinnedMeshRenderer).ToACSIIFBX(true);
                else if (context as MeshRenderer) fbx = (context as MeshRenderer).ToACSIIFBX();
                else continue;
                if (string.IsNullOrEmpty(fbx)) continue;
                if (System.IO.File.Exists(path)) AssetDatabase.DeleteAsset(path);
                System.IO.File.WriteAllText(path, fbx);
                AssetDatabase.Refresh();
            }

            SkinnContext.Finished();

        }

        [CtxMenuItem("SkinnedMeshRenderer/Export/FBX All Transforms",
            "Exports a single skinned mesh and all transforms under it's root." +
            "Multi-frame Blend-shapes, Blend-shape Normals, and Blend-shape Tangents are not supported.", 0)]
        public static void SkinnedRendererExportFBXAllTransforms()
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<SkinnedMeshRenderer>();
                if (SkinnEx.IsNullOrNotInAScene(context) || string.IsNullOrEmpty(context.name)) continue;
                if (!SkinnEx.HasMinimumRequirements(context)) continue;
                string path = EditorUtility.SaveFilePanelInProject("Export FBX", context.name, "fbx", "ACSIIFBX");
                if (path == "") continue;
                if (!path.EndsWith(".fbx")) Debug.LogWarning("file path should end with .FBX");
                string fbx = context.ToACSIIFBX(false);
                if (string.IsNullOrEmpty(fbx)) continue;
                if (System.IO.File.Exists(path)) AssetDatabase.DeleteAsset(path);
                System.IO.File.WriteAllText(path, fbx);
                AssetDatabase.Refresh();
            }

            SkinnContext.Finished();

        }
    }
}